import Request from './request'
import apiList from './apis.js'
import store from '@/utils/store/index.js'

const rhinoRequest = new Request();

export default function http(
	url,
	data = {},
	toastBefore = '', // 请求前加载提示
	toastAfter = true, // 请求后错误提示
) {
	let api = getApiPath(url);
	/* 请求之前拦截器 */
	rhinoRequest.interceptor.request((config, cancel) => {
		let token = uni.getStorageSync('token');
		if (api.auth && !token) {
      uni.reLaunch({
        url: '/pages/home/user'
      })
			store.dispatch('showAuthModal');
			uni.hideLoading()
			throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
		}
		token && rhinoRequest.setConfig(config => {
			config.header.token = token
		})
		if (toastBefore !== '') {
			uni.showLoading({
				title: toastBefore,
				mask: true
			});
		}
		return config
	});

	/* 请求之后拦截器 */
	rhinoRequest.interceptor.response((response) => {
		uni.hideLoading();
    
    const { success, errorMsg, errorCode, data } = response
    
    // token过期注销
    if (+errorCode === 401 || +errorCode === 500) {
      uni.reLaunch({
        url: '/pages/home/user'
      })
    	store.dispatch('logout');
    	store.dispatch('showAuthModal');
    	throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
    }
    
		if (!success) {
			if (toastAfter) {
				uni.showToast({
					title: errorMsg || '请求出错,稍后重试',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}
		}

		return {
      status: success ? 200 : errorCode,
      msg: success ? '成功' : errorMsg,
      data,
    }
	})
  
  console.log('api: ', api)

  if (api.method === 'GET' || api.method === 'get') {
    return rhinoRequest.get(api.url,
    	{
        params: data,
      },
    )
  } else {
    return rhinoRequest.request({
    	url: api.url,
    	data,
    	method: api.method
    })
  }
}

// 组装接口路径
function getApiPath(url) {
	let apiArray = url.split(".");
	let api = apiList;
	apiArray.forEach(v => {
		api = api[v];
	});
	return api;
}
